﻿#if UNITY_2017_1_OR_NEWER
using UnityEngine;
using UnityEngine.Playables;
using System.Collections.Generic;

namespace AudioStudio
{
    [System.Serializable]
    public class AudioPlayableAsset : PlayableAsset
    {
        public AudioEventPC playEvent;
        public AudioEventPC stopEvent;
        public bool Stop = false;
        public bool IsUpdatePosition = true;

        public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
        {
            var playable = ScriptPlayable<AnimationAudio>.Create(graph);
            playable.GetBehaviour().init(playEvent, stopEvent, go, Stop, IsUpdatePosition);

            return playable;
        }
    }

    public class AnimationAudio : PlayableBehaviour
    {
        private AudioEventPC playEvent;
        private AudioEventPC stopEvent;
        private AnimationSound animationSound;
        private bool Stop;

        public void init(AudioEventPC playevent, AudioEventPC stopevent, GameObject go, bool stop, bool isUpdatePosition, bool playerCtrl = false)
        {
            this.playEvent = playevent;
            this.stopEvent = stopevent;
            this.animationSound = go.GetComponent<AnimationSound>();
            if (this.animationSound == null)
            {
                this.animationSound = go.AddComponent<AnimationSound>();
                this.animationSound.IsUpdatePosition = isUpdatePosition;
            }
            this.animationSound.PlayerControl = playerCtrl;
            this.Stop = stop;
        }

        public override void OnBehaviourPlay(Playable playable, FrameData info)
        {
            base.OnBehaviourPlay(playable, info);
            if (this.playEvent != null && this.animationSound != null)
            {
                this.animationSound.Play(this.playEvent);
            }
        }

        public override void OnPlayableDestroy(Playable playable)
        {
            base.OnPlayableDestroy(playable);
            if (this.animationSound != null)
            {
                if (this.Stop)
                {
                    this.animationSound.Stop(this.playEvent);
                }
                if (this.stopEvent != null)
                {
                    this.animationSound.Play(this.stopEvent);
                }
            }
        }
    }
}
#endif